package cn.lcj.user.service.impl;

import cn.lcj.basic.exception.BusinessException;
import cn.lcj.basic.utils.Md5Utils;
import cn.lcj.basic.utils.StrUtils;
import cn.lcj.org.domain.Employee;
import cn.lcj.org.domain.Shop;
import cn.lcj.org.mapper.EmployeeMapper;
import cn.lcj.user.domain.Logininfo;
import cn.lcj.user.domain.User;
import cn.lcj.user.mapper.LogininfoMapper;
import cn.lcj.user.mapper.UserMapper;
import cn.lcj.user.service.IUserService;
import cn.lcj.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.validation.constraints.Email;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public void phoneRegister(Map<String, String> map) {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String pwd = map.get("pwd");
        String repwd = map.get("repwd");
        //一、校验
        //1.空值校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
                || StringUtils.isEmpty(pwd) || StringUtils.isEmpty(repwd)) {
            throw new BusinessException("请填好信息");
        }
        //校验密码是否一致
        if (!pwd.equals(repwd)) {
            throw new BusinessException("两次密码输入不一致，请重新输入");
        }
        //3.判断手机验证码是否为空，是否正确
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if (obj == null) {
            throw new BusinessException("手机验证码已经过期，请重新获取");
        }
        //是否正确
        if (!phoneCode.equals(obj.toString().split(":")[0])) {
            throw new BusinessException("手机验证码输入错误,请重新输入");
        }
        //二、添加到数据库
        //1.当将一个obj转化到另一个obj，且代码大量相同时，用obj2Obj
        User user = map2User(map);
        Logininfo logininfo = user2LoginInfo(user);

        //2.2先添加logininfo，因为主键自增后才能设置user里面loginif_id
         logininfoMapper.save(logininfo);
         //添加user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

    }

    @Override
    public void emailRegister(Map<String, String> map1) throws MessagingException {
        String email = map1.get("email");
        String password = map1.get("password");
        String passwordRepeat = map1.get("passwordRepeat");
        //一、校验
        //1.空值校验
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(passwordRepeat)) {
            throw new BusinessException("请填好完整信息");
        }
        //判断邮箱号是否已经注册过
        User user1 = userMapper.loadByEmail(email);
        if (user1 != null) {
            throw new RuntimeException("该邮箱已经被注册");
        }
        //校验密码是否一致
        if (!password.equals(passwordRepeat)) {
            throw new BusinessException("两次密码输入不一致，请重新输入");
        }
        //二、添加到数据库
        //1.当将一个obj转化到另一个obj，且代码大量相同时，用obj2Obj
          user1 = map2User1(map1);
        Logininfo logininfo = user2LoginInfo(user1);

        //2.2先添加logininfo，因为主键自增后才能设置user里面loginif_id
        logininfoMapper.save(logininfo);
        //添加user
        user1.setLogininfoId(logininfo.getId());
        userMapper.save(user1);
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        helper.setFrom("1907326859@qq.com");//平台邮箱
        helper.setSubject("邮箱激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
         user1 = userMapper.loadByEmail(email);
        helper.setText("<h1>你的邮箱已经注册!!!</h1><img src='http://123.207.27.208/" + user1.getId()+ "'>" +
                "<a href='http://127.0.0.1:8080/user/activeEmail/" + user1.getId() + "'>点击该链接激活</a>", true);
       /* //添加附件
        helper.addAttachment("p7.jpg",new File("C:\\Users\\Administrator\\Pictures\\photos\\p7.jpg"));
        helper.addAttachment("g1.gif", new File("C:\\Users\\Administrator\\Pictures\\g1.gif"));*/
        //收件人
        user1 = userMapper.loadById(user1.getId());
        helper.setTo(user1.getEmail());//改店长邮箱为真实邮箱
        javaMailSender.send(mimeMessage);
    }

    @Override
    public String activeState(Long id) {
        User user1  = userMapper.loadById(id);
        user1.setState(1);
        userMapper.update(user1);
        return "恭喜你，激活成功";
    }


    private Logininfo user2LoginInfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照属性同名原则进行属性拷贝【username，email，phone，salt，password】
        BeanUtils.copyProperties(user,logininfo);//采用的是setter getter原理
        logininfo.setType(1);//用户手机登录注册
        logininfo.setDisable(true);//手机验证码注册成功就可以使用
        return logininfo;
    }

    private User map2User(Map<String, String> map) {
        User user = new User();
        String phone = map.get("phone");
        user.setUsername(phone);
        user.setPhone(phone);
        String salt= StrUtils.getComplexRandomString(32);
        //生成32位的加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(map.get("pwd") + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }
    private Logininfo user12LoginInfo1(User user1) {
        Logininfo logininfo1 = new Logininfo();
        //按照属性同名原则进行属性拷贝【username，email，phone，salt，password】
        BeanUtils.copyProperties(user1,logininfo1);//采用的是setter getter原理
        logininfo1.setType(1);//用户手机登录注册
        logininfo1.setDisable(true);//手机验证码注册成功就可以使用
        return logininfo1;
    }

    private User map2User1(Map<String, String> map1) {
        User user1 = new User();
       String email = map1.get("email");
       user1.setUsername(email);
        user1.setEmail(email);
        String salt= StrUtils.getComplexRandomString(32);
        //生成32位的加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(map1.get("password") + salt);
        user1.setSalt(salt);
        user1.setPassword(md5Pwd);
        user1.setState(0);
        return user1;
    }
}